<?php

/**
 * Project form base class.
 *
 * @package    help
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormBaseTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
abstract class BaseFormDoctrine extends sfFormDoctrine
{
  public function setup()
  {
  }
  
  //Это костыль для бага симфонии, из-за которого не сохраняются связи многие-ко-многим в embedded forms
  //http://symfonyguide.wordpress.com/2009/09/28/symfony-forms-saving-process/
  public function saveEmbeddedForms($con = null, $forms = null)
  {
    if (is_null($con))
    {
      $con = $this->getConnection();
    }

    if (is_null($forms))
    {
      $forms = $this->embeddedForms;
    }

    foreach ($forms as $key => $form)
    {
      if ($form instanceof sfFormDoctrine)
      {
      	/*
      	 * --------------------
      	 * only modification
      	 */
      	if(method_exists(new $form(), 'doSaveManyToMany'))
      	{
          $form->doSaveManyToMany($con);
      	}
      	else
      	{
          $form->getObject()->save($con);
      	}
      	/*
      	 * --------------------
      	 */
        $form->saveEmbeddedForms($con);
      }
      else
      {
        $this->saveEmbeddedForms($con, $form->getEmbeddedForms());
      }
    }
  }


 
  public function bindEmbeddedForms($embedded_forms, $values)
  {
    if($this->isValid())
    {
      foreach ($embedded_forms as $name => $form)
      {
        $form->isBound = true;
	$form->values = $values[$name];

	if ($form->embeddedForms)
	{
	  $this->bindEmbeddedForms($form->embeddedForms, $values[$name]);
	}
      }
    }
  }
  

  public function doSaveManyToMany($con = null)
  {
    if (is_null($con))
    {
      $con = $this->getConnection();
    }

    $this->object->save($con);

   /*
    * Save the many-2-many relationship
    */
    foreach ($this->getObject()->getTable()->getRelations() as $relationName => $relation)
    {
      if ($relation instanceof Doctrine_Relation_Association)
      {
        call_user_func(array($this, 'save' . $relationName . 'List'), $con);
      }
    }
    $this->getObject()->save($con);
    $this->saveEmbeddedForms($con);
  }

  public function bind(array $taintedValues = null, array $taintedFiles = null) {

      parent::bind($taintedValues, $taintedFiles);
      $this->bindEmbeddedForms($this->embeddedForms, $this->getValues());

  }  
}
